const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.post('/add-news', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const {
    title,
    classid,
    news_type,
    cover,
    intro,
    tags,
    files,
    img,
    status,
    content,
  } = req.body
  if (
    !Bee.StringUtils.isNotBlank(title) ||
    !Bee.StringUtils.isNotBlank(intro) ||
    !Bee.StringUtils.isNotBlank(content) ||
    !Bee.StringUtils.isNumber(classid) ||
    !Bee.StringUtils.isNumber(status) ||
    !Bee.StringUtils.isNumber(news_type)
  )
    return handleError(10003, '参数错误')

  const authorid = validateTokenSuccess.id

  // 判断是否有当前栏目
  const [findClassError, findClassSuccess] = await to(
    db.query('SELECT count(*) FROM class WHERE id = ?', [classid])
  )
  if (findClassError || !findClassSuccess)
    return handleError(-1, findClassError)
  if (findClassSuccess[0]['count(*)'] !== 1) handleError(-1, '系统错误') // 没有栏目就响应错误

  const [addNewsError, addNewsSuccess] = await to(
    db.query(
      'INSERT INTO news (title, classid, created_time, updated_time, news_type, intro, cover, status, content, authorid, tags, files, img) VALUES (?, ?, NOW(), NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [
        title,
        classid,
        news_type,
        intro,
        cover ? cover : '',
        status,
        content,
        authorid,
        tags ? tags : '',
        files ? files : '',
        img,
      ]
    )
  )
  if (addNewsError || !addNewsSuccess) return handleError(-1, addNewsError)
  if (addNewsSuccess.affectedRows > 0) {
    return resp.json({
      code: 0,
      msg: status_code[0],
      data: {
        id: addNewsSuccess.insertId,
      },
    })
  }
  return handleError(-1, '系统错误')
})

module.exports = router
